<?php
class product_model extends CI_Model
{
	function __construct()
	{
		parent::__construct();
		$this->load->helper('img_helper');  
		$this->load->helper('str');
	}
	// Thông kê gian hang
	// Tong so san pham
	function get_total_product($bl_active)
	{
	  $this->db->select('ProductID');
	  $this->db->where('IsActive',$bl_active);
	  return $this->db->get('product')->num_rows();
	}
	// Tong so binh luận
	function get_total_comment($bl_active)
	{
	  $this->db->select('CommentID');
	  if($bl_active!=2)
	  {
		$this->db->where('IsActive',$bl_active);
	  }
	  return $this->db->get('productcomment')->num_rows();
	}  
	// Tong so don hang
	function get_total_order($Status)
	{
	  $this->db->select('CartID');
	  if($Status !=6){
		$this->db->where('Status',$Status);              
	  }
	  return $this->db->get('shoppingcart')->num_rows();
	}          
	  
	// End
	
	function getAllCat($cid,$num,$offset)
	{
		$this->db->order_by('Ordering','ASC');
		$this->db->where('ParentID',$cid);
		$query = $this->db->get('category',$num,$offset);
		return $query->result();
	}
	
	function getNumCat($cid)
	{
		$this->db->where('ParentID',$cid);
		$query = $this->db->get('category');
		return $query->num_rows();
	}
	
	function getMaincat()
	{
		$this->db->where('ParentID',0);
		$this->db->where('IsActive',1);
		$this->db->where('IsMainMenu',1);
		$this->db->order_by('Ordering','ASC');  
		$query = $this->db->get('category');
		return $query->result();
	}
	
	function getListSub($CategoryID)
	{
	  if($CategoryID==0){
		  return array();
	  }
	  $this->db->where('ParentID',$CategoryID);
	
	  $this->db->order_by('Ordering','ASC');           
	  $query = $this->db->get('category');
	  return $query->result();
	}
	
	function get_edit_cat($CategoryID)
	{
	  $this->db->where('CategoryID',$CategoryID);
	  $query = $this->db->get('category');
	  $data = $query->row(); 
	  return $data;
	} 
	
	function saveCat()
	{
	  $CategoryID = (int)$this->uri->segment(3);
	  $Parentid = (int)$this->input->post('ParentID');
	  $this->db->where('ParentID',$Parentid);
	  $this->db->order_by('Ordering','DESC');
	  if($check = $this->db->get('category')->row()){
		  $order = $check->Ordering;
	  }else{
		  $order = 0;
	  }
	  $data_insert = array(
			'CategoryName' => (string)$this->input->post('CategoryName'),
			'CategoryAlias' => strtolower(kodau($this->input->post('CategoryName'))),
			'ParentID' => $Parentid,
			'IsActive' => (int)$this->input->post('bl_active'),
			'IsMainMenu' => (int)$this->input->post('IsMainMenu'),
			'Level' => (int)$this->input->post('level'),
			'Ordering' => $order + 1
	  );
	  $data_update = array(
			'CategoryName' => (string)$this->input->post('CategoryName'),
			'CategoryAlias' =>  strtolower(kodau($this->input->post('CategoryName'))),
			'ParentID' => $Parentid,
			'IsActive' => (int)$this->input->post('bl_active'),
			'Level' => (int)$this->input->post('level'),
			'IsMainMenu' => (int)$this->input->post('IsMainMenu')
	  );
	  if($CategoryID !=0){
		  $this->db->where('CategoryID',$CategoryID);
		  if($this->db->update('category',$data_update))
		  {
			  /*$this->db->where('CategoryID',$CategoryID);
			  $this->db->delete('menufacture_cat');
			  $ar_id = $this->input->post('ar_id');
				for($i = 0; $i < sizeof($ar_id); $i ++) {
					if ($ar_id[$i]){
						$data_map = array(
							'CategoryID' => $CategoryID,
							'MenufactureID' => $ar_id[$i]
						);
						$this->db->insert('menufacture_cat',$data_map);
					}
				}*/                  
			  return true;
		  }else{
			  return false;
		  }
	  }else{
		  if($this->db->insert('category',$data_insert)){
			  return true;
		  }else{
			  return false;
		  }
	  }
	  
	}
	
	function get_all_is_mainmenu()
	{
	  $this->db->where('ParentID',0);
	  $this->db->where('IsActive',1);
	  $this->db->where('IsMainMenu',1);
	  $this->db->order_by('Ordering','ASC');
	  $query = $this->db->get('category');
	  return $query->result();
	}
	
	function get_ads_daugia()
	{
	  
	}
	
	function get_ads_by_cat($CategoryID)
	{          
	  $this->db->where('bl_active',1);
	  $this->db->where('CategoryID',$CategoryID);
	  $this->db->order_by('AdsID','DESC');
	  $query = $this->db->get('ads',2,0);
	  return $query->result();
	}
	
	function delcat($id)
	{
		$ar_cat = array($id);
		$this->db->where('ParentID',$id);
		$query = $this->db->get('category');
		$list = $query->result();
		if($query->num_rows() > 0){
			foreach($list as $rs):
				array_push($ar_cat,$rs->CategoryID);
			endforeach;
			
			$this->db->where_in('ParentID',$ar_cat);
			$query1 = $this->db->get('category');
			if($query1->num_rows() > 0){
				foreach($query1->result() as $rs):
					array_push($ar_cat,$rs->CategoryID);
				endforeach;
			}
		}          
		
		$this->db->where_in('CategoryID',$ar_cat);
		$query = $this->db->delete('category');
		if($query){
			$this->db->where_in('CategoryID',$ar_cat);
			//$this->db->delete('categoryproduct');
			$this->db->delete('category');
			return true;
		}else{
			return false;
		}          
	}
	
	/*****Product**********/
	function getAllProduct($cid, $num, $offset)
	{
		$this->db->where('bl_active',1);
		$query = $this->db->get('product',$num,$offset);
		return $query->result();
	}
	
	function getNumProduct($cid)
	{
		$this->db->where('bl_active',1);
		$query = $this->db->get('product');
		return $query->num_rows();
	}
	
	function get_info_product($ProductID)
	{
	  $this->db->where('ProductID',$ProductID);
	  $query = $this->db->get('product');
	  return $query->row();
	}
	
	function get_info_product_kind()
	{
	  $this->db->select('type_name, template');
	  $this->db->order_by('type_name',"asc");
	  $query = $this->db->get('producttype');
	  return $query->result();
	}
	
	function get_promotion_by_id($ProductID)
	{
	  $this->db->where('ProductID',$ProductID);
	  $query = $this->db->get('productpromotion');
	  return $query->row();
	}
	
	function get_discount_by_id($ProductID)
	{
	  $this->db->where('ProductID',$ProductID);
	  $query = $this->db->get('productdiscount');
	  return $query->row();
	}
	function get_shipping_by_id($ProductID)
	{
	  return $this->db->get_where('productshipping',array('ProductID'=> $ProductID))->row();
	}
	
	function get_gifts_by_id($ProductID)
	{
	  return $this->db->get_where('productgifts',array('ProductID'=>$ProductID))->row();
	}
	function getAllMenufacture()
	{
	  $this->db->order_by('MenufactureName', 'ASC');
	  $query = $this->db->get('menufacture');
	  return $query->result();
	}
	
	function get_menyfacture_by_id($MenufactureID,$CategoryID)
	{
	  $this->db->where('CategoryID',$CategoryID);
	  $this->db->where('MenufactureID',$MenufactureID);
	  if($this->db->get('menufacture_cat')->row()){
		  return true;
	  }else{
		  return false;
	  }
	}
	
	function get_info_cat($CategoryID)
	{
	  $list = '';
	  $info_cat = $this->check_category($CategoryID);
	  $cat1 = $info_cat->CategoryID;
	  if($info_cat->ParentID != 0){
		  $cat2 =$info_cat->ParentID;
		  $info_cat1 = $this->check_category($info_cat->ParentID);
		  if($info_cat1->ParentID !=0){
			  $cat3 = $info_cat1->ParentID;
			  return $cat3.'-'.$cat2.'-'.$cat1;
		  }else{
			  return $cat2.'-'.$cat1.'-0';
		  }
	  }else{
		  return $cat1.'-0-0';
	  }
	}
	
	function delproduct($id)
	{
		$this->db->where_in('ProductID',$id);
		$query = $this->db->delete('product');
		if($query)
		{
			$this->db->where('ProductID',$id);
			$this->db->delete('product');
			return true;
		}
		else
		{
			return false;
		}          
	}      
	
	/***********SEARCH**************/
	function get_array_cat_search($CategoryID)
	{
	  $ar_cat = array($CategoryID);
	  $info_cat = $this->check_parentid($CategoryID);	// level 2
	  if(count($info_cat) > 0)
	  {
		  foreach($info_cat as $rs):
				array_push($ar_cat,$rs->CategoryID); 
				$info_cat1 = $this->check_parentid($rs->CategoryID);	// level 3
				if(count($info_cat1) > 0)
				{
					foreach($info_cat1 as $rs1):
					array_push($ar_cat,$rs1->CategoryID);
					$info_cat2 = $this->check_parentid($rs1->CategoryID);	// level 4
					if(count($info_cat2) > 0)
					{
						foreach($info_cat2 as $rs2):
						array_push($ar_cat,$rs2->CategoryID);
						endforeach;
					}   
					endforeach;
				}                 
		  endforeach;
	
	  }
	  return $ar_cat;
	}
	
	function getAllProductExport($cid,$keyword='')
	{
	  $ar_cid = $this->get_array_cat_search($cid);
	  $this->db->select('product.*,categoryproduct.*');
	  $this->db->join('categoryproduct','categoryproduct.ProductID = product.ProductID');
	  if($cid!=0){
		  $this->db->where_in('categoryproduct.CategoryID',$ar_cid);
	  }
	  if($keyword!=''){
		  $this->db->like('product.ProductName',$keyword);
	  }
	  
	  $query = $this->db->get('product');
	  return $query->result();
	}
	
	function getAllProductSea($cid, $keyword, $num, $offset, $ord=0)
	{
	  $promo = (int) $this->input->post('promo');
	  
	  $ar_cid = $this->get_array_cat_search($cid);			
	  //trit($ar_cid);
	  
	  $this->db->select('product.*,category.*');
	  $this->db->join('category','category.ProductID = product.ProductID');
	  
	  if(!empty($promo)) $this->db->where('product.IsHome',$promo);
	  
	  if($cid!=0){
		  $this->db->where_in('category.CategoryID',$ar_cid);
	  }
	  if($keyword!=''){
		  $this->db->like('product.ProductName',$keyword);
	  }
	  
	  switch($ord)
	  {
		case 1 :
			$this->db->order_by('product.Ordering',"ASC"); break ;
		case 2 :
			$this->db->order_by('product.LastUpdate',"DESC"); break ;
		case 3 :
			$this->db->order_by('product.Price',"ASC"); break ;
		case 4 :
			$this->db->order_by('product.PriceHN',"ASC"); break ;	
		case 5 :
			$this->db->order_by('product.OrderHN',"ASC"); break ;		
		default :
			$this->db->order_by('product.LastUpdate',"DESC"); break ;  
	  }
	  
	  $query = $this->db->get('product',$num,$offset);
	  return $query->result();
	}
	
	function getNumProductSea($cid,$keyword)
	{
	  $ar_cid = $this->get_array_cat_search($cid);
	  
	  $this->db->select('product.*,category.*');
	  $this->db->join('category','category.ProductID = product.ProductID');
	  if($cid!=0){
		  $this->db->where_in('category.CategoryID',$ar_cid);
	  }
	  if($keyword!=''){
		  $this->db->like('product.ProductName',$keyword);
	  }          
	  $query = $this->db->get('product');
	  return $query->num_rows();
	}
	
	function check_category($CategoryID)
	{
	  $this->db->where('CategoryID',$CategoryID);
	  $query = $this->db->get('category');
	  return $query->row();
	} 
	
	function check_parentid($CategoryID)
	{          
	  $this->db->where('ParentID',$CategoryID);
	  $this->db->order_by('Ordering','ASC');
	
	  $query = $this->db->get('category');
	  return $query->result();          
	}
	
	function get_all_shippingtype(){
	  return $this->db->get_where('shippingtype',array('bl_active'=>1))->result();
	}     
	
	function saveProduct()
	{
	  $ProductID = (int)$this->uri->segment(3);
	  $CategoryID = (int)$this->input->post('CategoryID');
	  
	  $data = array(
		'ProductCode' => strtoupper($this->input->post('ProductCode')),
		'ProductName' => $this->input->post('ProductName'),
		'Alias' =>  strtolower(kodau($this->input->post('ProductName'))),
		'ProductImg' => $this->input->post('ContentImg'),
		'Price' => to_number($this->input->post('Price')),
		'CategoryID' => (int)$this->input->post('CategoryID'),
		'VAT' 		=> (int)$this->input->post('VAT'),
		'CategoryID' => (int)$this->input->post('CategoryID'),
		'ProductFunc' => (string)$this->input->post('ProductFunc'),
		'ProductStatus' => (int)$this->input->post('ProductStatus'),
		'ProductStatusText' => $this->input->post('ProductStatusText'),
		'ProductSize' => (string)$this->input->post('ProductSize'),
		'ProductWeight' => $this->input->post('ProductWeight'),
		'bl_active' => (int)$this->input->post('bl_active'),
		'IsHome' => (int)$this->input->post('IsHome'),
		'UserID' => 0,
		'LastUpdate' => date("Y-m-d H:i:s")
	  );
	  if($ProductID !=0)
	  {
		// Update products
		$this->db->where('ProductID',$ProductID);
		if($this->db->update('product',$data)){
			return true;
		}else{
			return false;
		}
	  }
	  else
	  {
		  if($this->db->insert('product',$data)){
			  return true;
		  }else{
			  return false;
		  }
	  }
	}
	
	//**********************************************************************************************
	// Xoa tang pham
	function delete_tangpham($id)
	{
	  $this->db->where('ProductID',$id);
	  $this->db->delete('productgifts');
	}
	
	function get_list_gifts($ProductID)
	{
	  $this->db->where('ProductID',$ProductID);
	  $this->db->order_by('GiftsID','asc');
	  return $this->db->get('productgifts')->result();
	}
	
	function get_img_by_session($session)
	{
	  $this->db->where('ImageSession',$session);
	  $query = $this->db->get('productimage');
	  return $query->result();
	}
	
	function get_img_by_product_id($ProductID)
	{
	  $this->db->where('ProductID',$ProductID);
	  return $this->db->get('productimage')->result();
	}
	
	function add_img($path,$ProductID,$session)
	{
	  if($path!=''){
		  fn_resize_image('../uploads/images/'.$path,'../uploads/product/200/'.$path,200,200);
		  fn_resize_image('../uploads/images/'.$path,'../uploads/product/80/'.$path,80,80);
		  fn_resize_image('../uploads/images/'.$path,'../uploads/product/40/'.$path,40,40);
		  fn_resize_image('../uploads/images/'.$path,'../uploads/product/30/'.$path,30,30);
		  
		  //image_thumb($ProductID,$path,55,45);
		  
	  $data = array(
		'ImagePath' => $path,
		'ProductID' => (int)$ProductID,
		'ImageSession' => ($ProductID!=0)?'':$session
	  );
	  $this->db->insert('productimage',$data);
	  }
	  return true;
	}
	
	function getListImg($ProductID,$session)
	{
	  if($ProductID != 0){
		  $this->db->where('ProductID',$ProductID);
		  $query = $this->db->get('productimage');
		  return $query->result();
	  }else{
		  $this->db->where('ImageSession',$session);
		  $query = $this->db->get('productimage');
		  return $query->result();              
	  }
	}
	// ********************************************************************************************  
	function move_up($id_nwc)
	{
	// move a category one level up
	// get this one's properties
	$this_one = $this->get_cat_info($id_nwc);
	// get this id_nwc's weight
	$this_order = $this_one->Ordering;
	$this_pid   = $this_one->ParentID;
	// do nothing if this one is the first item
	if($this_order > 1){
		// get the first nearest lighter item
		$sql = "SELECT CategoryID, Ordering FROM category WHERE (Ordering < '$this_order') AND ParentID = $this_pid ORDER BY Ordering DESC LIMIT 0,1";
		$replaced = $this->db->query($sql)->row();
		// switch their weights
		$swap_id = $replaced->CategoryID;
		$swap_order = $replaced->Ordering;
		$this->db->query("UPDATE category SET Ordering ='$swap_order' WHERE CategoryID='$id_nwc'");
		$this->db->query("UPDATE category SET Ordering ='$this_order' WHERE CategoryID='$swap_id'");
	
		return TRUE;
	}
	return FALSE;
	}
	
	function move_down($id_nwc)
	{
	// move a category one level down
	// get this one's properties
	$this_one = $this->get_cat_info($id_nwc);
	// get this id_nwc's weight
	$this_order = $this_one->Ordering;
	$this_pid   = $this_one->ParentID;
	// do nothing if this one is the last item
	$heaviest = $this->get_heaviest($this_pid);
	if($this_order <  $heaviest){
		// get the first heavier item
		$sql = "SELECT CategoryID, Ordering FROM category WHERE (Ordering > '$this_order') AND ParentID = $this_pid ORDER BY Ordering ASC LIMIT 0,1";
		$replaced = $this->db->query($sql)->row();
		// switch their weights
		$swap_id = $replaced->CategoryID;
		$swap_order = $replaced->Ordering;
		$this->db->query("UPDATE category SET Ordering ='$swap_order' WHERE CategoryID='$id_nwc'");
		$this->db->query("UPDATE category SET Ordering ='$this_order' WHERE CategoryID='$swap_id'");
	
		return TRUE;
	}
	return FALSE;
	}
	
	function get_cat_info($id_nwc)
	{
	// get a category info
	// input : $cat_id, single value
	// return : a row
	$search['CategoryID'] = $id_nwc;
	$rs = $this->db->get_where("category", $search, 1);
	return $rs->num_rows() ? $rs->row() : false;
	// to be revised: what if $id_nwc is not existing?
	}
	
	function get_heaviest($nwc_pid)
	{
	// get heaviest item in a branch (nwc_pid)
	$sql = "SELECT MAX(ordering) AS ordering FROM category WHERE ParentID ='$nwc_pid'";
	return $this->db->query($sql)->first_row()->ordering;
	}    
	
	// Promotion
	function listpromotion($num,$offset)
	{
		$this->db->select('productdiscount.*, product.*');
		$this->db->join('product','product.ProductID = productdiscount.ProductID');
		$this->db->where('productdiscount.DiscountNumber !=',0);         
		$this->db->order_by('productdiscount.DiscountEndDate',"DESC");
		$query = $this->db->get('productdiscount',$num,$offset);
		return $query->result();
	}
}
?>
